﻿using System;
using System.Collections.Concurrent;
using System.ServiceModel;

namespace Sharp.Infrastructure.WCF
{
    /// <inheritdoc />
    /// <summary>
    ///     表示Channel Factory管理器。
    /// </summary>
    internal sealed class ChannelFactoryManager : DisposableObject
    {
        #region 私有字段

        private static readonly ConcurrentDictionary<Type, ChannelFactory> Factories =
            new ConcurrentDictionary<Type, ChannelFactory>();

        public static readonly ChannelFactoryManager Instance = new ChannelFactoryManager();

        #endregion
 
        static ChannelFactoryManager()
        {
        }

        private ChannelFactoryManager()
        {
        }
         
        protected override void Dispose(bool disposing)
        {
            if (!disposing) return;

            foreach (var factory in Factories.Values)
            {
                try
                {
                    factory.Close();
                }
                catch
                {
                    factory.Abort();
                }
            }
                
            Factories.Clear();
        }
          
        /// <summary>
        ///     获取与指定服务契约类型相关的Channel Factory实例。
        /// </summary>
        /// <typeparam name="T">服务契约的类型。</typeparam>
        /// <returns>与指定服务契约类型相关的Channel Factory实例。</returns>
        /// <remarks>线程安全</remarks>
        public ChannelFactory<T> GetFactory<T>() where T : class, IApplicationServiceContract
        {
            var factory = Factories.GetOrAdd(typeof (T), x => new ChannelFactory<T>(typeof(T).Name));

            return factory as ChannelFactory<T>;

        } 
    }
}